

template <typename T>
class UnionFindSet
{
public:
    UnionFindSet()
    {
    }

    template <typename TContainer>
    UnionFindSet(const TContainer &container)
    {
        auto begin = container.begin();
        auto end = container.end();
        while (begin != end)
        {
            m[*begin] = *begin;
            ++begin;
            ++_groupCount;
        }
    }

    void insert(const T &value)
    {
        if (!m.count(value))
        {
            m[value] = value;
            ++_groupCount;
        }
    }

    bool exist(const T &value)
    {
        return m.count(value);
    }

    T find(const T &value)
    {
        if (m[value] == value)
        {
            return value;
        }
        return m[value] = find(m[value]);
    }

    void join(const T &value1, const T &value2)
    {
        if (!m.count(value1))
        {
            m[value1] = value1;
            ++_groupCount;
        }
        if (!m.count(value2))
        {
            m[value2] = value2;
            ++_groupCount;
        }
        if (find(value1) != find(value2))
        {
            m[find(value1)] = find(value2);
            --_groupCount;
        }
    }

    int groupCount()
    {
        return _groupCount;
    }

private:
    std::unordered_map<T, T> m;
    int _groupCount = 0;
};

class Solution
{
public:
    int closedIsland(vector<vector<int>> &grid)
    {
        UnionFindSet<int> s;
        s.insert(-1);
        int m = grid.size();
        int n = grid[0].size();
        auto encode = [&](int i, int j)
        {
            return m * j + i;
        };

        for (int i = 0; i < m; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                if (grid[i][j] != 0)
                {
                    continue;
                }

                int coordinate = encode(i, j);
                s.insert(coordinate);
                if (i == 0 || j == 0 || i == m - 1 || j == n - 1)
                {
                    s.join(coordinate, -1);
                    continue;
                }

                if (grid[i - 1][j] == 0)
                {
                    s.insert(encode(i - 1, j));
                    s.join(coordinate, encode(i - 1, j));
                }
                if (grid[i + 1][j] == 0)
                {
                    s.insert(encode(i + 1, j));
                    s.join(coordinate, encode(i + 1, j));
                }
                if (grid[i][j - 1] == 0)
                {
                    s.insert(encode(i, j - 1));
                    s.join(coordinate, encode(i, j - 1));
                }
                if (grid[i][j + 1] == 0)
                {
                    s.insert(encode(i, j + 1));
                    s.join(coordinate, encode(i, j + 1));
                }
            }
        }
        return s.groupCount() - 1;
    }
};